package com.aichan.aibi.utils;

import com.aichan.aibi.model.entity.User;
import com.aichan.aibi.model.entity.login.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * ThreadLocal 工具类
 *
 * @Author: mengyu
 * @Date: 2024/10/1
 */
public class ThreadLocalUtil {

    public static ThreadLocal<Object> threadLocal = new ThreadLocal<>();

    public static void setObject(Object obj) {
        threadLocal.set(obj);
    }

    public static Object getObject() {
        return threadLocal.get();
    }

    public static void removeObject() {
        threadLocal.remove();
    }

    /**
     * 获取登录后的 User 对象
     *
     * @return User
     */
    public static User getUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser();
    }

    public static Long getUserId() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getId();
    }
}
